package com.hsd.znsh.service.impl;

import com.hsd.znsh.entity.Batch;
import com.hsd.znsh.entity.Pick;
import com.hsd.znsh.enums.BatchStatusEnum;
import com.hsd.znsh.repository.BatchRepository;
import com.hsd.znsh.repository.PickRepository;
import com.hsd.znsh.service.PickService;
import com.hsd.znsh.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/*
 * @auther: wangjiacai
 *
 * @create: 2018-05-02 17:48:37
 */
@Service
public class PickServiceImpl extends BaseServiceImpl implements PickService {

    @Autowired
    private PickRepository pickRepository;

    @Autowired
    private BatchRepository batchRepository;


    @Override
    public List<Pick> getPickListByBatchId(Integer batchId) {
        return pickRepository.findByBatchIdOrderByPickSnDesc(batchId);
    }

    @Override
    public Pick addPick(Pick pick, Integer batchId) {
        Batch batch=batchRepository.findOne(batchId);
        if(batch.getStatus()!=BatchStatusEnum.ENDED.getCode()){
            batch.setStatus(BatchStatusEnum.PICKING.getCode());
        }
        batchRepository.save(batch);

        pick.setBatchId(batchId);
        String pickSn=pickRepository.findMaxPickSnByBatchId(batchId);
        pick.setPickSn(batch.getBatchSn()+"-"+getPickSn(pickSn));
        return pickRepository.save(pick);
    }

    private String getPickSn(String pickSn){
        if(StringUtils.isEmpty(pickSn)){
            return "-001";
        }
        Integer num=Integer.parseInt(pickSn.substring(pickSn.lastIndexOf("-")+1))+1;
        String number=num+"";
        while(number.length()<3){
            number="0"+number;
        }
        return number;
    }



}
